# @FileName  : msql.py
# @Time      : 2021/10/6 0014  9:15
# @Author    : LuZhaoHui
# @Software  : PyCharm

from queue import Queue

from pymysql import *

from core.tool import *

MAX_MYSQLQUEUENUMS = 9


class mysqlProc():
    def __init__(self, dbPara):
        self.host = dbPara['Ip']
        self.port = dbPara['Port']
        self.user = dbPara['User']
        self.password = dbPara['Pass']
        self.db = dbPara['Database']
        self.op = 0
        self.ver = 0
        self.conn = None
        self.cur = None
        self.err = None
        self.ret = 0
        self.status = False
        self.queue = Queue(MAX_MYSQLQUEUENUMS)
        print("mysql thread start")
        # self._thread = threading.Thread(target=self.getQueue)
        # self._thread.start()

    def __del__(self):
        print("mysql thread stop")
        # stop_thread(self._thread)

    def setSys(self, op, ver):
        self.op = op
        self.ver = ver

    def exit(self):
        self.close()
        self.__del__()

    def close(self):
        if self.cur != None:
            self.cur.close()
            self.cur = None
        if self.conn != None:
            self.conn.close()
            self.conn = None

    def open(self):
        self.err = None
        try:
            if self.conn == None:
                self.err = ''
                if len(self.host) > 0 and self.port > 0 and len(self.user) > 0:
                    self.conn = connect(host=self.host,
                                        port=self.port,
                                        user=self.user,
                                        passwd=self.password,
                                        db=self.db)
            if self.conn != None and self.cur == None:
                self.cur = self.conn.cursor()
        except Exception as e:
            self.err = e
            self.conn = None
            self.close()
            saveLog(curFunc(e), log='error')
        self.status = self.conn != None
        return self.status

    # def getQueue(self):
    #     while True:
    #         if not self.queue.empty():
    #             sqls = self.queue.get()
    #             # print(sqls)
    #             self.getExec(sqls)
    #         time.sleep(1)

    # def putQueue(self, sqls):
    #     try:
    #         self.queue.put(sqls)
    #     except Exception as e:
    #         saveLog(curFunc(e), log='error')
    #     return self.queue.qsize()

    def getExec(self, sqls, all=False):
        self.err = None
        self.ret = 0
        saveLog(sqls)
        try:
            if self.open():
                self.ret = self.cur.execute(sqls)
                self.conn.commit()
        except Exception as e:
            self.close()
            self.err = e
            saveLog(curFunc(e), log='error')
        if self.ret > 0:
            if all:
                data = self.cur.fetchall()
            else:
                data = self.cur.fetchone()
            return data
        return 0

    # 建立项目记录-addWork
    # def addWork(self, workName, workPath, workLst, workNums, workType):
    #     sqls = "call addWork(\'%s\',\'%s\',\'%s\',%d,%d,%d) " \
    #            % (workName, workPath, workLst,
    #               workNums, workType, self.op)
    #     return self.getExec(sqls)

    # 建立项目图片记录-addWorkImg
    def addWorkImg(self, workId, imgFile, imgSize, imgDpi, imgByte, isList):
        sqls = "call addWorkImg(%d,\'%s\',%d,%d,%d,%d,%d,%d,%d,%d,%d,%d) " \
               % (workId, imgFile, imgSize[0], imgSize[1], imgDpi[0], imgDpi[1],
                  imgByte, isList[0], isList[1], isList[2], isList[3], self.op)
        return self.getExec(sqls)

    # 建立打印记录-addPhoto
    def addPhoto(self, workId, photoConf, photoType, photoNums, photoStep, photoTime):
        sqls = "call addPhoto(%d,\'%s\',%d,%d,%d,%d,%d) " \
               % (workId, photoConf, photoType, photoNums, photoStep, photoTime, self.op)
        return self.getExec(sqls)

    # 打印结束
    def modPhoto(self, photoId):
        sqls = "call modPhoto(%d,%d) " % (photoId, self.op)
        return self.getExec(sqls)

    # 建立打印日志记录-addPhotoLog
    def addPhotoLogEx(self, ip, work, photoId, beginTime, endTime, photoType, report):
        sqls = "call addPhotoLogEx(\'%s\',\'%s\',%d,%d,%d,\'%s\',\'%s\',\'%s\',\'%s\') " % \
               (ip, work, int(photoId), beginTime, endTime, photoType, report, self.op, self.ver)
        return self.getExec(sqls)

    # 行为日志记录-addActLog
    def addActLog(self, name, actInfo):
        sqls = "call addActLog(\'%s\',%d,\'%s\',\'%s\',\'%s\') " % \
               (name, nowDateTimeInt(), actInfo, self.op, self.ver)
        # if thread:
        #     return self.putQueue(sqls)
        # else:
        return self.getExec(sqls)

    # 查询打印记录-queryPrint
    # 查询打印日志记录-queryPrintLog

    # 查询分卷数据-queryImageMergeData
    def queryWorkData(self, unitId, workId):
        sqls = "call queryImageMergeData(%d,%d) " % (unitId, workId)
        return self.getExec(sqls, all=True)

    # 查询操作员数据-getOps()
    def queryOps(self):
        sqls = "call getOps()"
        return self.getExec(sqls, all=True)

    # 查询打印服务器数据-getPrints()
    def queryPrints(self):
        sqls = "call getPrints()"
        return self.getExec(sqls, all=True)

    # 查询打印服务器数据-getPrints()
    def getPara(self, type):
        sqls = "call getPara(%d)" % (type)
        return self.getExec(sqls, all=True)

    # def getMysqlPhotoLogRecord(self, logType, ):

    # 添加项目记录-addWork
    def addWork(self, printIp, workName, workPath, workLst,
                workNums, workMainNums, workByteM, workType):
        # thread=False):
        sqls = "call addWork(\'%s\',\'%s\',\'%s\',\'%s\',%d,%d,%d,%d,\'%s\',\'%s\')" % \
               (printIp, workName, workPath, workLst,
                workNums, workMainNums, workByteM, workType,
                self.op, self.ver)
        # if thread:
        #     return self.putQueue(sqls)
        # else:
        return self.getExec(sqls)

    # 添加项目记录-addWork
    def delWork(self, printIp, workName):
        # , thread=False):
        sqls = "call delWork(\'%s\',\'%s\')" % (printIp, workName)
        # if thread:
        #     return self.putQueue(sqls)
        # else:
        return self.getExec(sqls)

    def addWorkList(self, workName, photoId, photoPath,
                    photoWidth, photoHeight, photoStd, photoFace, photoType, photoByte,
                    photoExpo, photoLight, photoLum):
        # , thread=False):
        sqls = "call addWorkList(\'%s\',%d,\'%s\',%d,%d,%d,%d,%d,%d,%d,%.3f,%.3f) " % \
               (workName, photoId, photoPath,
                photoWidth, photoHeight, photoStd, photoFace, photoType, photoByte,
                photoExpo, photoLight, photoLum)
        # if thread:
        #     return self.putQueue(sqls)
        # else:
        return self.getExec(sqls)


def procLogQueue(self):
    pass


class MysqlProc(threading.Thread):
    def __init__(self, msql, ):
        super().__init__()
        self.mysql = msql

    def run(self):
        self.mysql.open()
